package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserDaoImpl implements UserDao {


    @Override
    public User login(User user) {
        User uus = null;
        SqlSession sqlSession= getsqls();
        uus = sqlSession.selectOne("UserMapper.findUserByUP", user);
        System.out.println(uus);
        System.out.println(sqlSession);
        sqlSession.close();
        return uus;
    }

    private SqlSession getsqls() {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = build.openSession();
        return sqlSession;
    }

    @Override
    public List<User> list() {
        SqlSession sqlSession = getsqls();
        List<User> list = sqlSession.selectList("UserMapper.findAllUser");
        sqlSession.close();
        return list;

    }

    public void addUser(User user) {
        SqlSession sqlSession = getsqls();
        sqlSession.insert("UserMapper.addUser", user);
        sqlSession.commit();
        sqlSession.close();
    }





}
